package com.iris.thread.cylicBarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 项目: thinking
 * 包名: com.iris.thread.cylicBarrier
 * 作者: victor
 * 日期: 2016年11月1日
 * 说明: CylicBarrierTest
 * 可循环利用的栅栏...和countDownLatch比较
 * Barrier是等待指定数量线程到达再继续处理； 
	Latch是等待指定事件变为指定状态后发生再继续处理，对于CountDown就是计数减为0的事件，但你也可以实现或使用其他Latch就不是这个事件了... 
	Barrier是等待指定数量任务完成，Latch是等待其他任务完成指定状态的改变再继续。。。
 */
public class CylicBarrierTest {

/**
 * public CyclicBarrier(int parties, Runnable barrierAction) { }//参数barrierAction为当这些线程都达到barrier状态时会执行的内容。
   public CyclicBarrier(int parties) { }
   
   public int await()
   public int await(long timeout, TimeUnit unit) //unit:如果还有线程没有到达barrier状态就直接让到达barrier的线程执行后续任务
 */
	
	
	public static void main(String[] args) {
		int count = 3;
//		CyclicBarrier cb = new CyclicBarrier(count);
		CyclicBarrier cb = new CyclicBarrier(count,new CylicBarrierEndRunnable());
		Thread th1= new Thread(new CylicBarrierRunnable(cb),"th1");
		Thread th2= new Thread(new CylicBarrierRunnable(cb),"th2");
		Thread th3= new Thread(new CylicBarrierRunnable(cb),"th3");
		th1.start();
		th2.start();
		th3.start();
		
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//CyclicBarrier 可以重复利用
		System.out.println("==========================3000");
		Thread th4= new Thread(new CylicBarrierRunnable(cb),"th4");
		Thread th5= new Thread(new CylicBarrierRunnable(cb),"th5");
		Thread th6= new Thread(new CylicBarrierRunnable(cb),"th6");
		th4.start();
		th5.start();
		th6.start();
	}
	
}

class CylicBarrierRunnable implements Runnable{
	private CyclicBarrier cb ;
	public CylicBarrierRunnable(CyclicBarrier cb){
		this.cb = cb;
	}
	
	
	public void run() {
		try {
			System.out.println("CylicBarrierRunnable=========sleep");
			Thread.sleep(1000);
			System.out.println("CylicBarrierRunnable=========await");
			cb.await();
			Thread.sleep(1000);
			System.out.println("CylicBarrierRunnable=========await==========end");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
		
	}
	
}

class CylicBarrierEndRunnable implements Runnable{

	public void run() {
		System.out.println("=============CylicBarrierEndRunnable");
		
	}
	
}


